package com.by.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.by.rpc.annotation.RpcMethod;
import com.by.rpc.annotation.RpcService;
import com.by.user.api.service.IUserService;
import com.by.user.api.vo.UserVo;
import com.by.user.entity.UserEntity;
import com.by.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
@RpcService(interfaceClass = IUserService.class, version = "1.0.0", group = "default")
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public UserVo register(String username, String password) {
        // 实现用户注册逻辑
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(username);
        userEntity.setPassword(encryptPassword(password));
        userMapper.insert(userEntity);
        UserVo user = new UserVo();
        BeanUtils.copyProperties(userEntity, user);
        // 调用mapper保存用户

        return user;
    }

    @Override
    public UserVo getUserById(Long id) {
        // 实现根据ID获取用户逻辑
        UserEntity userEntity = userMapper.selectById(id);
        UserVo user = new UserVo();
        if (userEntity != null) {
            BeanUtils.copyProperties(userEntity, user);
        }
        return user;
    }

    /**
     * 加密密码
     *
     * @param password 原始密码
     * @return 加密后的密码
     */


    @Override
    public UserVo login(String username, String password) {
        // 实现用户登录逻辑
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
//        queryWrapper.eq("password", encryptPassword(password));
        queryWrapper.eq("password", password);

        UserEntity userEntity = userMapper.selectOne(queryWrapper);
        UserVo user = new UserVo();
        if (userEntity != null) {
            BeanUtils.copyProperties(userEntity, user);
        }
        return user;
    }

    private String encryptPassword(String password) {
        try {
            // 获取 MD5 消息摘要实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 计算哈希值
            byte[] hashBytes = md.digest(password.getBytes());

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = String.format("%02x", b);
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            // 处理算法不存在的异常
            throw new RuntimeException("MD5 algorithm not found", e);
        }
    }
}